﻿using System;
using Cysharp.Threading.Tasks;
using UnityEngine;
using YooAsset;
using Path = System.IO.Path;

namespace UniFramework.Asset
{
    public class RemoteServices : IRemoteServices
    {
        private string t = "http://192.168.0.107/2024-12-13-1117/";

        public string GetRemoteMainURL(string fileName)
        {
            string path = Path.Combine(t, fileName);
            Debug.Log(path);
            return path;
        }

        public string GetRemoteFallbackURL(string fileName)
        {
            string path = Path.Combine(t, fileName);
            Debug.Log(path);
            return path;
        }
    }

    public class HostAssetSystem : BaseAssetSystem
    {
        public override async UniTask Init(string defaultPackageName, Action initFinishCallBack)
        {
            await base.Init(defaultPackageName, initFinishCallBack);
            IRemoteServices remoteServices = new RemoteServices();
            var cacheFileSystem = FileSystemParameters.CreateDefaultCacheFileSystemParameters(remoteServices);
            var buildinFileSystem = FileSystemParameters.CreateDefaultBuildinFileSystemParameters();
            var initParameters = new HostPlayModeParameters();
            /*
                在编辑器下运行HostPlayMode模式的时候，会提示你本地找不到清单的版本文件。
                这是因为初始化创建Package的时候，指定了内置文件系统的初始化参数。
                如果本地没有任何内置资源文件（首包文件），可以尝试将内置文件系统的初始化参数类设置为NULL。
            */
            initParameters.BuildinFileSystemParameters = null;
            initParameters.CacheFileSystemParameters = cacheFileSystem;
            var initOperation = _defaultPackage.InitializeAsync(initParameters);
            await initOperation;
            await RequestPackageVersion();
            await UpdatePackageManifest();
            await TryUpdateAssets();
            initFinishCallBack?.Invoke();
            UniLogger.Log("HostAssetSystem Init Success");
        }

        protected override async UniTask RequestPackageVersion()
        {
            await base.RequestPackageVersion();
            UniLogger.Log($"pass RequestPackageVersion 当前版本：{packageVersion}");
            UniLogger.Log("HostAssetSystem RequestPackageVersion Success");
        }

        protected override async UniTask UpdatePackageManifest()
        {
            await base.UpdatePackageManifest();
            UniLogger.Log($"pass UpdatePackageManifest 当前版本：{packageVersion}");
            UniLogger.Log("HostAssetSystem RequestPackageVersion Success");
        }

        private async UniTask<bool> TryUpdateAssets()
        {
            UniLogger.Warning("TryUpdateAssets");
            var package = _defaultPackage;
            var downloader = package.CreateResourceDownloader(10, 10);
            if (downloader.TotalDownloadCount == 0)
            {
                UniLogger.Log("wxy------------------->没有需要更新的资源");
                return false;
            }

            UniLogger.Warning("TryUpdateAssets have asset need update");
            // downloader.OnDownloadErrorCallback += OnDownloadError;
            // downloader.OnDownloadProgressCallback += OnDownloadProgress;
            // downloader.OnDownloadOverCallback += OnDownloadOver;
            // downloader.OnStartDownloadFileCallback += OnStartDownloadFile;

            downloader.BeginDownload();

            await downloader;
            if (downloader.Status == EOperationStatus.Succeed)
            {
                UniLogger.Log("下载完成");
                return true;
            }

            UniLogger.Log("下载失败");
            return false;
        }

        private void OnDownloadError(string fileName, string error)
        {
            UniLogger.Error($"下载失败：{fileName}，{error}");
        }

        private void OnDownloadProgress(int totalDownloadCount, int currentDownloadCount, long totalDownloadBytes,
            long currentDownloadBytes)
        {
            UniLogger.Error(
                $"下载中：{currentDownloadCount}/{totalDownloadCount}，{currentDownloadBytes}/{totalDownloadBytes}");
        }

        private void OnStartDownloadFile(string fileName, long sizeBytes)
        {
            UniLogger.Log($"开始下载：{fileName}，{sizeBytes}");
        }

        private void OnDownloadOver(bool isSucceed)
        {
            UniLogger.Log($"下载完成：{isSucceed}");
        }
    }
}